home *** CD-ROM | disk | FTP | other *** search
/ American Osteopathic Ass…tion Yearbook 2005 & 2006 / American Osteopathic Association Yearbook 2005 & 2006.iso / mac / app / sets.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2004-07-22  |  22.4 KB  |  510 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.3)
  3.  
  4. """Classes to represent arbitrary sets (including sets of sets).
  5.  
  6. This module implements sets using dictionaries whose values are
  7. ignored.  The usual operations (union, intersection, deletion, etc.)
  8. are provided as both methods and operators.
  9.  
  10. Important: sets are not sequences!  While they support 'x in s',
  11. 'len(s)', and 'for x in s', none of those operations are unique for
  12. sequences; for example, mappings support all three as well.  The
  13. characteristic operation for sequences is subscripting with small
  14. integers: s[i], for i in range(len(s)).  Sets don't support
  15. subscripting at all.  Also, sequences allow multiple occurrences and
  16. their elements have a definite order; sets on the other hand don't
  17. record multiple occurrences and don't remember the order of element
  18. insertion (which is why they don't support s[i]).
  19.  
  20. The following classes are provided:
  21.  
  22. BaseSet -- All the operations common to both mutable and immutable
  23.     sets. This is an abstract class, not meant to be directly
  24.     instantiated.
  25.  
  26. Set -- Mutable sets, subclass of BaseSet; not hashable.
  27.  
  28. ImmutableSet -- Immutable sets, subclass of BaseSet; hashable.
  29.     An iterable argument is mandatory to create an ImmutableSet.
  30.  
  31. _TemporarilyImmutableSet -- A wrapper around a Set, hashable,
  32.     giving the same hash value as the immutable set equivalent
  33.     would have.  Do not use this class directly.
  34.  
  35. Only hashable objects can be added to a Set. In particular, you cannot
  36. really add a Set as an element to another Set; if you try, what is
  37. actually added is an ImmutableSet built from it (it compares equal to
  38. the one you tried adding).
  39.  
  40. When you ask if `x in y' where x is a Set and y is a Set or
  41. ImmutableSet, x is wrapped into a _TemporarilyImmutableSet z, and
  42. what's tested is actually `z in y'.
  43.  
  44. """
  45. __all__ = [
  46.     'BaseSet',
  47.     'Set',
  48.     'ImmutableSet']
  49. from itertools import ifilter, ifilterfalse
  50.  
  51. class BaseSet(object):
  52.     '''Common base class for mutable and immutable sets.'''
  53.     __slots__ = [
  54.         '_data']
  55.     
  56.     def __init__(self):
  57.         '''This is an abstract class.'''
  58.         if self.__class__ is BaseSet:
  59.             raise TypeError, 'BaseSet is an abstract class.  Use Set or ImmutableSet.'
  60.         
  61.  
  62.     
  63.     def __len__(self):
  64.         '''Return the number of elements of a set.'''
  65.         return len(self._data)
  66.  
  67.     
  68.     def __repr__(self):
  69.         """Return string representation of a set.
  70.  
  71.         This looks like 'Set([<list of elements>])'.
  72.         """
  73.         return self._repr()
  74.  
  75.     __str__ = __repr__
  76.     
  77.     def _repr(self, sorted = False):
  78.         elements = self._data.keys()
  79.         if sorted:
  80.             elements.sort()
  81.         
  82.         return '%s(%r)' % (self.__class__.__name__, elements)
  83.  
  84.     
  85.     def __iter__(self):
  86.         '''Return an iterator over the elements or a set.
  87.  
  88.         This is the keys iterator for the underlying dict.
  89.         '''
  90.         return self._data.iterkeys()
  91.  
  92.     
  93.     def __cmp__(self, other):
  94.         raise TypeError, "can't compare sets using cmp()"
  95.  
  96.     
  97.     def __eq__(self, other):
  98.         if isinstance(other, BaseSet):
  99.             return self._data == other._data
  100.         else:
  101.             return False
  102.  
  103.     
  104.     def __ne__(self, other):
  105.         if isinstance(other, BaseSet):
  106.             return self._data != other._data
  107.         else:
  108.             return True
  109.  
  110.     
  111.     def copy(self):
  112.         '''Return a shallow copy of a set.'''
  113.         result = self.__class__()
  114.         result._data.update(self._data)
  115.         return result
  116.  
  117.     __copy__ = copy
  118.     
  119.     def __deepcopy__(self, memo):
  120.         '''Return a deep copy of a set; used by copy module.'''
  121.         deepcopy = deepcopy
  122.         import copy
  123.         result = self.__class__()
  124.         memo[id(self)] = result
  125.         data = result._data
  126.         value = True
  127.         for elt in self:
  128.             data[deepcopy(elt, memo)] = value
  129.         
  130.         return result
  131.  
  132.     
  133.     def __or__(self, other):
  134.         '''Return the union of two sets as a new set.
  135.  
  136.         (I.e. all elements that are in either set.)
  137.         '''
  138.         if not isinstance(other, BaseSet):
  139.             return NotImplemented
  140.         
  141.         result = self.__class__()
  142.         result._data = self._data.copy()
  143.         result._data.update(other._data)
  144.         return result
  145.  
  146.     
  147.     def union(self, other):
  148.         '''Return the union of two sets as a new set.
  149.  
  150.         (I.e. all elements that are in either set.)
  151.         '''
  152.         return self | other
  153.  
  154.     
  155.     def __and__(self, other):
  156.         '''Return the intersection of two sets as a new set.
  157.  
  158.         (I.e. all elements that are in both sets.)
  159.         '''
  160.         if not isinstance(other, BaseSet):
  161.             return NotImplemented
  162.         
  163.         if len(self) <= len(other):
  164.             (little, big) = (self, other)
  165.         else:
  166.             (little, big) = (other, self)
  167.         common = ifilter(big._data.has_key, little)
  168.         return self.__class__(common)
  169.  
  170.     
  171.     def intersection(self, other):
  172.         '''Return the intersection of two sets as a new set.
  173.  
  174.         (I.e. all elements that are in both sets.)
  175.         '''
  176.         return self & other
  177.  
  178.     
  179.     def __xor__(self, other):
  180.         '''Return the symmetric difference of two sets as a new set.
  181.  
  182.         (I.e. all elements that are in exactly one of the sets.)
  183.         '''
  184.         if not isinstance(other, BaseSet):
  185.             return NotImplemented
  186.         
  187.         result = self.__class__()
  188.         data = result._data
  189.         value = True
  190.         selfdata = self._data
  191.         otherdata = other._data
  192.         for elt in ifilterfalse(otherdata.has_key, selfdata):
  193.             data[elt] = value
  194.         
  195.         for elt in ifilterfalse(selfdata.has_key, otherdata):
  196.             data[elt] = value
  197.         
  198.         return result
  199.  
  200.     
  201.     def symmetric_difference(self, other):
  202.         '''Return the symmetric difference of two sets as a new set.
  203.  
  204.         (I.e. all elements that are in exactly one of the sets.)
  205.         '''
  206.         return self ^ other
  207.  
  208.     
  209.     def __sub__(self, other):
  210.         '''Return the difference of two sets as a new Set.
  211.  
  212.         (I.e. all elements that are in this set and not in the other.)
  213.         '''
  214.         if not isinstance(other, BaseSet):
  215.             return NotImplemented
  216.         
  217.         result = self.__class__()
  218.         data = result._data
  219.         value = True
  220.         for elt in ifilterfalse(other._data.has_key, self):
  221.             data[elt] = value
  222.         
  223.         return result
  224.  
  225.     
  226.     def difference(self, other):
  227.         '''Return the difference of two sets as a new Set.
  228.  
  229.         (I.e. all elements that are in this set and not in the other.)
  230.         '''
  231.         return self - other
  232.  
  233.     
  234.     def __contains__(self, element):
  235.         """Report whether an element is a member of a set.
  236.  
  237.         (Called in response to the expression `element in self'.)
  238.         """
  239.         
  240.         try:
  241.             return element in self._data
  242.         except TypeError:
  243.             transform = getattr(element, '__as_temporarily_immutable__', None)
  244.             if transform is None:
  245.                 raise 
  246.             
  247.             return transform() in self._data
  248.  
  249.  
  250.     
  251.     def issubset(self, other):
  252.         '''Report whether another set contains this set.'''
  253.         self._binary_sanity_check(other)
  254.         if len(self) > len(other):
  255.             return False
  256.         
  257.         for elt in ifilterfalse(other._data.has_key, self):
  258.             return False
  259.         
  260.         return True
  261.  
  262.     
  263.     def issuperset(self, other):
  264.         '''Report whether this set contains another set.'''
  265.         self._binary_sanity_check(other)
  266.         if len(self) < len(other):
  267.             return False
  268.         
  269.         for elt in ifilterfalse(self._data.has_key, other):
  270.             return False
  271.         
  272.         return True
  273.  
  274.     __le__ = issubset
  275.     __ge__ = issuperset
  276.     
  277.     def __lt__(self, other):
  278.         self._binary_sanity_check(other)
  279.         if len(self) < len(other):
  280.             pass
  281.         return self.issubset(other)
  282.  
  283.     
  284.     def __gt__(self, other):
  285.         self._binary_sanity_check(other)
  286.         if len(self) > len(other):
  287.             pass
  288.         return self.issuperset(other)
  289.  
  290.     
  291.     def _binary_sanity_check(self, other):
  292.         if not isinstance(other, BaseSet):
  293.             raise TypeError, 'Binary operation only permitted between sets'
  294.         
  295.  
  296.     
  297.     def _compute_hash(self):
  298.         result = 0
  299.         for elt in self:
  300.             result ^= hash(elt)
  301.         
  302.         return result
  303.  
  304.     
  305.     def _update(self, iterable):
  306.         data = self._data
  307.         if isinstance(iterable, BaseSet):
  308.             data.update(iterable._data)
  309.             return None
  310.         
  311.         value = True
  312.  
  313.  
  314.  
  315. class ImmutableSet(BaseSet):
  316.     '''Immutable set class.'''
  317.     __slots__ = [
  318.         '_hashcode']
  319.     
  320.     def __init__(self, iterable = None):
  321.         '''Construct an immutable set from an optional iterable.'''
  322.         self._hashcode = None
  323.         self._data = { }
  324.         if iterable is not None:
  325.             self._update(iterable)
  326.         
  327.  
  328.     
  329.     def __hash__(self):
  330.         if self._hashcode is None:
  331.             self._hashcode = self._compute_hash()
  332.         
  333.         return self._hashcode
  334.  
  335.     
  336.     def __getstate__(self):
  337.         return (self._data, self._hashcode)
  338.  
  339.     
  340.     def __setstate__(self, state):
  341.         (self._data, self._hashcode) = state
  342.  
  343.  
  344.  
  345. class Set(BaseSet):
  346.     ''' Mutable set class.'''
  347.     __slots__ = []
  348.     
  349.     def __init__(self, iterable = None):
  350.         '''Construct a set from an optional iterable.'''
  351.         self._data = { }
  352.         if iterable is not None:
  353.             self._update(iterable)
  354.         
  355.  
  356.     
  357.     def __getstate__(self):
  358.         return (self._data,)
  359.  
  360.     
  361.     def __setstate__(self, data):
  362.         (self._data,) = data
  363.  
  364.     
  365.     def __hash__(self):
  366.         '''A Set cannot be hashed.'''
  367.         raise TypeError, "Can't hash a Set, only an ImmutableSet."
  368.  
  369.     
  370.     def __ior__(self, other):
  371.         '''Update a set with the union of itself and another.'''
  372.         self._binary_sanity_check(other)
  373.         self._data.update(other._data)
  374.         return self
  375.  
  376.     
  377.     def union_update(self, other):
  378.         '''Update a set with the union of itself and another.'''
  379.         self |= other
  380.  
  381.     
  382.     def __iand__(self, other):
  383.         '''Update a set with the intersection of itself and another.'''
  384.         self._binary_sanity_check(other)
  385.         self._data = (self & other)._data
  386.         return self
  387.  
  388.     
  389.     def intersection_update(self, other):
  390.         '''Update a set with the intersection of itself and another.'''
  391.         self &= other
  392.  
  393.     
  394.     def __ixor__(self, other):
  395.         '''Update a set with the symmetric difference of itself and another.'''
  396.         self._binary_sanity_check(other)
  397.         data = self._data
  398.         value = True
  399.         for elt in other:
  400.             if elt in data:
  401.                 del data[elt]
  402.                 continue
  403.             data[elt] = value
  404.         
  405.         return self
  406.  
  407.     
  408.     def symmetric_difference_update(self, other):
  409.         '''Update a set with the symmetric difference of itself and another.'''
  410.         self ^= other
  411.  
  412.     
  413.     def __isub__(self, other):
  414.         '''Remove all elements of another set from this set.'''
  415.         self._binary_sanity_check(other)
  416.         data = self._data
  417.         for elt in ifilter(data.has_key, other):
  418.             del data[elt]
  419.         
  420.         return self
  421.  
  422.     
  423.     def difference_update(self, other):
  424.         '''Remove all elements of another set from this set.'''
  425.         self -= other
  426.  
  427.     
  428.     def update(self, iterable):
  429.         '''Add all values from an iterable (such as a list or file).'''
  430.         self._update(iterable)
  431.  
  432.     
  433.     def clear(self):
  434.         '''Remove all elements from this set.'''
  435.         self._data.clear()
  436.  
  437.     
  438.     def add(self, element):
  439.         '''Add an element to a set.
  440.  
  441.         This has no effect if the element is already present.
  442.         '''
  443.         
  444.         try:
  445.             self._data[element] = True
  446.         except TypeError:
  447.             transform = getattr(element, '__as_immutable__', None)
  448.             if transform is None:
  449.                 raise 
  450.             
  451.             self._data[transform()] = True
  452.  
  453.  
  454.     
  455.     def remove(self, element):
  456.         '''Remove an element from a set; it must be a member.
  457.  
  458.         If the element is not a member, raise a KeyError.
  459.         '''
  460.         
  461.         try:
  462.             del self._data[element]
  463.         except TypeError:
  464.             transform = getattr(element, '__as_temporarily_immutable__', None)
  465.             if transform is None:
  466.                 raise 
  467.             
  468.             del self._data[transform()]
  469.  
  470.  
  471.     
  472.     def discard(self, element):
  473.         '''Remove an element from a set if it is a member.
  474.  
  475.         If the element is not a member, do nothing.
  476.         '''
  477.         
  478.         try:
  479.             self.remove(element)
  480.         except KeyError:
  481.             pass
  482.  
  483.  
  484.     
  485.     def pop(self):
  486.         '''Remove and return an arbitrary set element.'''
  487.         return self._data.popitem()[0]
  488.  
  489.     
  490.     def __as_immutable__(self):
  491.         return ImmutableSet(self)
  492.  
  493.     
  494.     def __as_temporarily_immutable__(self):
  495.         return _TemporarilyImmutableSet(self)
  496.  
  497.  
  498.  
  499. class _TemporarilyImmutableSet(BaseSet):
  500.     
  501.     def __init__(self, set):
  502.         self._set = set
  503.         self._data = set._data
  504.  
  505.     
  506.     def __hash__(self):
  507.         return self._set._compute_hash()
  508.  
  509.  
  510.